<?php

namespace App\Sys\Services;

use App\Services\CommonBaseService;
use App\Sys\Models\SysI18nMachineTransModel;
use App\Sys\Models\SysI18nResourceModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class SysI18nService extends CommonBaseService
{

    private $baiduAppId = '';
    private $baiduSecret = '';
    private $buiduTransApi = 'https://fanyi-api.baidu.com/api/trans/vip/translate';
    private $transModel;


    /**
     * SysI18nService constructor.
     * @param SysI18nResourceModel $model
     * @param SysI18nMachineTransModel $transModel
     */
    public function __construct(SysI18nResourceModel $model, SysI18nMachineTransModel $transModel)
    {
        $this->model = $model;
        $this->transModel = $transModel;
    }

    /**
     * 确认机器翻译结果
     * @param array $resourceIds
     */
    public function confirmMachineTrans(array $resourceIds)
    {
        $this->model->confirmMachineTrans($resourceIds);
    }

    /**
     * 分页查询国际化资源
     * @param $appId string 应用ID
     * @param $module string 模块ID
     * @param $key string 键
     * @param $content string 中文内容
     * @param $auditLang string 审核语言
     * @param $pageSize 页码
     * @return array
     */
    public function listResource($appId, $module, $key, $content, $auditLang, $pageSize)
    {
        return $this->model->listResource($appId, $module, $key, $content, $auditLang, $pageSize);
    }

    /**
     *
     * @param $q
     * @param $from
     * @param $to
     * @return mixed|null
     */
    public function translate($q, $from, $to)
    {
        $salt = time();
        $sign = md5($this->baiduAppId.$q.$salt.$this->baiduSecret);
        $url = $this->buiduTransApi
            ."?q=".urlencode($q)."&from=$from&to=$to&appid={$this->baiduAppId}&salt=$salt&sign=$sign";
        $res = file_get_contents($url);
        $res = getHttpContent('GET', $this->buiduTransApi, [
            'q'=>$q,
            'from'=>$from,
            'to'=>$to,
            'appid'=>$this->baiduAppId,
            'salt'=>$salt,
            'sign'=>$sign,
        ]);
        $res = json_decode($res['response'], true);
        if (!empty($res['trans_result'])) {
            if (count($res['trans_result']) > 1) {
                return array_column($res['trans_result'], 'dst');
            } else {
                return $res['trans_result'][0]['dst']??null;
            }
        } else {
            Log::error(json_encode($res));
            return null;
        }
        if (!empty($res['trans_result'][0])) {
            return $res['trans_result'][0]['dst']??null;
        } else {
            Log::error(json_encode($res));
            return null;
        }
    }

    /**
     * 获取系统所有的资源文件
     * @param $appId string 应用ID
     * @param $module string 模块
     * @return \Illuminate\Support\Collection
     */
    public function getAppResource($appId, $module = null)
    {
        return $this->model->getAppResource($appId, $module);
    }

    /**
     * 批量保存
     * @param $dataList array 数据记录
     */
    public function saveResources(array $dataList)
    {
        return $this->model->insertAll($dataList);
    }

    /**
     * 获取语言国际化数据
     * @param $appId 应用ID
     * @param $locale 本地化语言
     * @return array
     */
    public function getAppLocale($appId, $locale)
    {
        $list = $this->model->getAppLocale($appId, $locale);
        $json = [];
        foreach ($list as &$v) {
            $v = (array)$v;
            $json[$v['module']][$v['key']] = $v[$locale]??'';
        }
        //空格
        $json['common']['space'] = $locale === "en_us" ? " " : "";
        return $json;
    }

    /**
     * 机器翻译
     */
    public function autoMachineTrans()
    {
        set_time_limit(0);
        $lang = 'en_us';
        $transCount = 0;
        do {
            $transList = $this->model->getTransList($lang, 40);
            $transCount += count($transList);
            $insertList = [];
            $updateList = [];
            foreach ($transList as &$v) {
                $v = (array)$v;
                $transContent = null;
                //$transContent = $this->translate($v['zh_cn'], 'zh', $lang);
               // $transContent = $this->gptTrans($v['zh_cn'], $lang);
                if (!$transContent) {
                    continue;
                }
                $data = [
                    'resource_id'=>$v['id'],
                    $lang => $transContent
                ];
                if (!empty($data[$lang]) && is_array($data[$lang])) {
                    $data[$lang] = implode("\n", $data[$lang]);
                }
                if (!$v['trans_id']) {
                    $insertList[] = $data;
                } else {
                    $updateList[] = $data;
                }
            }
            DB::transaction(function () use($insertList, $updateList) {
                if ($insertList) {
                    $this->transModel->insertAll($insertList);
                }
                if ($updateList) {
                    foreach ($updateList as &$o) {
                        $this->transModel->updateData($o);
                    }
                }

            });
        } while (count($transList) > 0);
        return $transCount;
    }
}
